//
//  MONetWork.m
//  emmoDiary
//
//  Created by miki on 2020/3/18.
//  Copyright © 2020 miki. All rights reserved.
//

#import "EMNetWork.h"
#define tx_key @"21cd7f6dc2dc66326e8b4c85228ed8e8"

@interface EMNetWork()

@end

@implementation EMNetWork
static EMNetWork *_instance = nil;


+ (EMNetWork *)shareManager{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [self manager];
    });
    return _instance;
}

- (instancetype)initWithBaseURL:(NSURL *)url{
    if (self = [super initWithBaseURL:nil]) {
        
        self.requestSerializer = [AFJSONRequestSerializer serializer];
        self.responseSerializer = [AFHTTPResponseSerializer serializer];
        self.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"image/jpeg", @"image/png",@"application/octet-stream",@"text/plain",@"*/*", nil];
        
        self.requestSerializer.timeoutInterval = 20;
        self.securityPolicy.allowInvalidCertificates = YES;
        self.securityPolicy.validatesDomainName = NO;
        
    }
    return self;
}

+ (NSInteger)networkType {
    AFNetworkReachabilityStatus status = [AFNetworkReachabilityManager sharedManager].networkReachabilityStatus;
    if (status == AFNetworkReachabilityStatusNotReachable) {
        return 1;
    } else if (status == AFNetworkReachabilityStatusReachableViaWWAN) {
        return 2;
    } else if (status == AFNetworkReachabilityStatusReachableViaWiFi) {
        return 3;
    } else {
        return 0;
    }
}

- (NSURLSessionDataTask *)em_post:(NSString *)url
                           params:(NSDictionary *)params
                              hud:(NSString *)hud
                        showError:(BOOL)showError
                          success:(void(^)(EMApiModel *api))success
                             fail:(void(^)(void))fail{
    
    if (hud) {
        if (hud.length > 0) {
            [EMHudManager show:hud];
        }else{
            [EMHudManager show];
        }
    }
    
    if ([url containsString:@"wxV3/app"] || [url containsString:@"ali/app"]) {
        url = [EMBasePayURL stringByAppendingString:url];
    }else if ([url containsString:@"pay/goods/list"]) {
        url = [EMBaseGoodsURL stringByAppendingString:url];
    }else if ([url containsString:@"notice/"]) {
        url = [EMBaseMessageURL stringByAppendingString:url];
    }else{
        url =  [EMBaseURL stringByAppendingString:url];
    }
    
    self.requestSerializer = [AFJSONRequestSerializer serializer];
    
    [self.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    NSString *token = [USUser user].token;
    if (token.length > 0) {
        [self.requestSerializer setValue:token forHTTPHeaderField:@"token"];
    }
    
    //网警要求header
    NSMutableDictionary *mergeParams = [NSMutableDictionary dictionary];

    [mergeParams setValue:[USUser user].userId forKey:@"userId"];
    
//    NSString *originalString = [USUserInfo userInfo].mobile ?:@"";
//    if (originalString.length > 0) {
//        NSData *data = [originalString dataUsingEncoding:NSUTF8StringEncoding];
//        NSString *base64Encoded = [data base64EncodedStringWithOptions:0];
//        
//        [mergeParams setValue:base64Encoded forKey:@"phoneNumber"];
//    }

    [mergeParams setValue:[UIDevice jk_platformString] forKey:@"phoneModel"];
    [mergeParams setValue:@"1" forKey:@"SystemType"];
    [mergeParams setValue:[NSObject jk_version] forKey:@"appVersion"];
    [mergeParams setValue:[@([EMNetWork networkType]) stringValue] forKey:@"networkStatus"];
    
    [mergeParams setValue:[[NSUserDefaults standardUserDefaults] objectForKey:@"lat"] forKey:@"lat"];
    [mergeParams setValue:[[NSUserDefaults standardUserDefaults] objectForKey:@"lng"] forKey:@"lng"];
    
    // actionType   1:发表情；2:发布评论
//    if ([url containsString:@"emmo/shareEmmo"]) {
//        [mergeParams setValue:@"1" forKey:@"actionType"];
//    }else if ([url containsString:@"comment/addComment"]){
//        [mergeParams setValue:@"2" forKey:@"actionType"];
//    }
    
    
    [mergeParams enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        if (obj) {
            [self.requestSerializer setValue:obj forHTTPHeaderField:key];
        }
    }];
    
    NSMutableDictionary *params_ = [NSMutableDictionary dictionaryWithDictionary:params];
    if (![params.allKeys containsObject:@"userId"]) {
        params_[@"userId"] = [USUser user].userId;
    }
    params_[@"version"] = [NSObject jk_version];
    params_[@"sharedSpaceId"] = [USUser user].sharedSpaceId;
    NSLog(@"url = %@ \n  sharedSpaceId = %@ \n request = %@",url,[USUser user].sharedSpaceId,params_);
    NSURLSessionDataTask *task = [self POST:url parameters:params_ headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [EMHudManager dismiss];
        if (![responseObject isKindOfClass:[NSData class]]) {
            return;
        }
        NSDictionary *dic = [responseObject mj_JSONObject];
                NSLog(@"url => %@ \n responseObject => %@",url,dic);
        EMApiModel *api = [EMApiModel mj_objectWithKeyValues:dic];
        if (api.success == NO) {
            if (api.code == NetworkErrorCode_noToken || api.code == NetworkErrorCode_failureToken || api.code == NetworkErrorCode_destroy) {
                if (api.code == NetworkErrorCode_failureToken) {
                    [[UIWindow keyWindow]makeToast:@"账号已在其他设备登录"];
                }
                [USUser cleanUserInfo];
            }else{
                if (api.msg.length > 0 && showError) {
                    [[UIWindow keyWindow]makeToast:api.msg];
                }
            }
           
        }
        !success?:success(api);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [EMHudManager dismiss];
        
        if (showError) {
            NSString *msg = error.localizedDescription;
            if (msg.length == 0) {
                msg = [NSString stringWithFormat:@"wow something bad happen-%ld",(long)error.code];
            }
            [[UIWindow keyWindow]makeToast:msg];
        }
                NSLog(@"%@",error);
        
        !fail?:fail();
    }];
    
    return task;
}

- (void)em_uploadImage:(UIImage *)image
               showHud:(BOOL)showHud
                 isPng:(BOOL)isPng
               success:(void(^)(NSString *fileId))success
                  fail:(void(^)(void))fail{
    
    if (showHud) {
        [EMHudManager show];
    }
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSData *data;
        
        if (isPng) {
            data = UIImagePNGRepresentation(image);
        }else{
            data = [UIImage jk_compressImage:image toMaxLength:1024 maxWidth:image.size.width];
        }
        
        if (data == nil) {
            data = UIImagePNGRepresentation(image);
        }
        
        if (data == nil) {
            [UIWindow.keyWindow makeToast:@"图片压缩失败"];
            return;
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            NSString *url =  [EMBaseURL stringByAppendingString:@"file/uploadFile"];
            if (data == nil) {
                return;
            }
            
            [self POST:url parameters:nil headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
                
                NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
                formatter.dateFormat =@"yyyyMMddHHmmss";
                NSString *dateStr = [formatter stringFromDate:[NSDate date]];
                NSString *fileName = [NSString stringWithFormat:@"%@.jpg", dateStr];
                [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/png"];
                
            } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                [EMHudManager dismiss];
                NSDictionary *dic = [responseObject mj_JSONObject];
                EMApiModel *api = [EMApiModel mj_objectWithKeyValues:dic];
                if (api.success == NO) {
                    [EMTool showAlert:api.msg msg:nil completion:nil];
                    return;
                }
                NSString *fileId = api.data[@"fileId"];
                !success?:success(fileId);
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
                [EMHudManager dismiss];
                NSString *msg = error.localizedDescription;
                if (msg.length == 0) {
                    msg = error.description;
                }
                [EMTool showAlert:msg msg:nil completion:nil];
                !fail?:fail();
                
            }];
        });
        
    });
}

- (NSURLSessionDataTask *)tx_post:(NSString *)path
                           params:(id)params
                          success:(void(^)(MOTXApiModel *api))success
                             fail:(void(^)(void))fail{
    
    NSMutableDictionary *params_ = [NSMutableDictionary dictionaryWithDictionary:params];
    params_[@"key"] = tx_key;
    
    self.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    NSURLSessionDataTask *task = [self POST:path parameters:params_ headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        @try {
            
            MOTXApiModel *apiModel = [MOTXApiModel mj_objectWithKeyValues:responseObject];
            !success?:success(apiModel);
            
        } @catch (NSException *exception) {
            
            NSLog(@"解析数据出错");
            
        } @finally {
            
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error.description);
        
        !fail?:fail();
    }];
    
    
    
    return task;
}

@end


@implementation MOTXApiModel

- (BOOL)success{
    return self.code == 200?YES:NO;
}

@end


@implementation EMApiModel

- (BOOL)success{
    return self.code == 200?YES:NO;
}

@end
